package com.gz2;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.zip.GZIPOutputStream;

public class ClientSocket {

    public static void main(String[] args) throws IOException {
        Socket socket = new Socket(InetAddress.getLocalHost(),9999);
        System.out.println("客户端 clientSocket "+socket.getClass());

//Socket只能接受和发送字节流，若要发送和接受字符流(文本文件),要用转换流(OuntputStreamWriter以及..)转换成字符流

        OutputStream outputStream = socket.getOutputStream();
//        outputStream.write("hello,server".getBytes());
        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
        bufferedWriter.write("你好，服务端 字符流");
        bufferedWriter.newLine();//表示输入结束(换行符),并且要求对方使用readline(注:如果使用while(..)接受出错，就不用newline())
        bufferedWriter.flush();//因为下面有socket.shutdownOutput()，这不是关闭，所以要在这个指令之前
                                //用flush()刷新才能将内容写成成功，否则不会写入
        System.out.println("发送成功");

        //如果要接收消息，要先shutdown(注:只有socket.getOutputStream()的socket需要shutdown
        //socket.getInputStream()不需要)
        socket.shutdownOutput();
        InputStream inputStream = socket.getInputStream();
//        byte[] buffer = new byte[1024];
//        int readlen=0;
//        while((readlen=inputStream.read(buffer))!=-1){
//            System.out.println(new String(buffer,0,readlen));
//        }
//        System.out.println("接收成功");
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        String s =bufferedReader.readLine();
        System.out.println(s);


        //必须关闭
        bufferedReader.close();
        bufferedWriter.close();
        inputStream.close();
        outputStream.close();
        socket.close();
        System.out.println("客户端关闭");


    }
}
